package xyz.ranyh.jobclient.http;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.List;

import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import xyz.ranyh.jobclient.util.JobBean;

/**
 * Created by rany on 1/4/17.
 */

public class GetStarJobTask extends AsyncTask<Void, Void, JSONObject> {
    private OkHttpClient client = new OkHttpClient();
    private List<JobBean> jobs;
    private GetJoblistener listener;

    public GetStarJobTask(List<JobBean> jobs) {
        this.jobs = jobs;
    }

    public void setGetJoblistener(GetStarJobTask.GetJoblistener listener) {
        this.listener = listener;
    }

    public interface GetJoblistener {
        void onSuccess(JSONObject res);
    }

    @Override
    protected JSONObject doInBackground(Void... params) {
        try {
            String credential = Credentials.basic(Resource.getInstance().token, "");
            Request request =  new Request.Builder()
                    .url(Url.GET_STAR_JOB_URL)
                    .addHeader("Authorization", credential)
                    .addHeader("accept", "application/json")
                    .build();
            Response response = client.newCall(request).execute();

            String responseText = response.body().string();
            JSONTokener resJson = new JSONTokener(responseText);
            JSONObject bodyJson = (JSONObject) resJson.nextValue();

            return bodyJson;

        } catch (Exception e) {
            Log.d("Register task", e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONObject res) {
        super.onPostExecute(res);
        if (res == null) return;
        try {
            JSONArray jobList = res.getJSONArray("jobs");
            for (int i = 0;i < jobList.length();i++) {
                JSONObject item = (JSONObject)jobList.get(i);

                JobBean mJB = new JobBean();
                mJB.setId(item.getInt("id"));
                mJB.setTitle(item.getString("title"));
                mJB.setUrl(item.getString("url"));
                mJB.setRefUrl(item.getString("ref_url"));
                mJB.setTags(item.getString("tags"));
                mJB.setFollowerCount(item.getInt("follower_count"));
                mJB.setOpenDate(item.getString("open_date"));
                mJB.setPublishedDate(item.getString("published_date"));
                mJB.setOpenDateInt(item.getInt("open_date_int"));
                mJB.setAlarm(item.getString("alarm"));

                jobs.add(mJB);
            }
//            jobsListAdapter.notifyDataSetChanged();
            listener.onSuccess(res);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
